package cn.ddiancan.xddcloud.ddccore.error;

import java.util.Map;

import cn.ddiancan.xddcloud.common.exception.ServiceException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.ServletWebRequest;

@Slf4j
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class DefaultErrorController implements ErrorController {

    @Autowired
    private ErrorAttributes errorAttributes;

    @RequestMapping
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        ServletWebRequest webRequest = new ServletWebRequest(request);
        Throwable error = errorAttributes.getError(webRequest);
        log.error("系统异常", error);
        String errorMsg = error.getMessage();
        int status;
        if (error instanceof ServiceException serviceException) {
            status = serviceException.getRuntimeExceptionCode();
            errorMsg = StringUtils.hasText(errorMsg) ? errorMsg : serviceException.getRuntimeExceptionMessage();
        } else if (error instanceof IllegalArgumentException) {
            status = 400;
        } else if (error instanceof AuthenticationException) {
            status = 403;
        } else {
            status = 500;
        }
        Map<String, Object> errorAttributeMap =
            errorAttributes.getErrorAttributes(webRequest, ErrorAttributeOptions.defaults());
        errorAttributeMap.put("status", status);
        errorAttributeMap.put("error", errorMsg);
        return ResponseEntity.status(status).contentType(MediaType.parseMediaType("application/json;charset=UTF-8"))
            .body(errorAttributeMap);
    }

}
